package cn.wolfcode.crm.web.filter;

import cn.wolfcode.crm.util.JSONResult;
import com.alibaba.fastjson.JSON;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;

public class MyFormAuthenticationFilter extends FormAuthenticationFilter {
    protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response) throws Exception {
        response.setContentType("text/json; Charset=utf-8");
        response.getWriter().print(JSON.toJSONString(new JSONResult()));
        return false;
    }

    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
        String errorMsg="登录错误,未知异常";
        if(e instanceof UnknownAccountException){
            errorMsg = "账户不存在";
        }else if (e instanceof IncorrectCredentialsException){
            errorMsg="密码错误";
        }
        response.setContentType("text/json; Charset:utf-8");
        try {
            response.getWriter().print(JSON.toJSONString(new JSONResult().mark(errorMsg)));
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        e.printStackTrace();

        return false;
    }
}
